/**
 * Excel模板管理器
 * 负责管理各种业务类型的Excel模板配置
 */

/**
 * 工单模板配置
 */
export const workOrderTemplate = {
  type: 'workOrder',
  name: '工单数据模板',
  description: '用于导入工单相关数据',
  businessType: 'workOrder',
  sheets: [
    {
      name: '工单信息',
      dataSource: 'workOrders',
      columns: [
        {
          field: 'workOrderId',
          label: '工单编号',
          dataType: 'string',
          required: true,
          width: 15,
          validator: 'workOrderId',
          example: 'W-001'
        },
        {
          field: 'orderId',
          label: '订单编号',
          dataType: 'string',
          required: true,
          width: 15,
          example: 'O-1001'
        },
        {
          field: 'productId',
          label: '产品编号',
          dataType: 'string',
          required: true,
          width: 15,
          validator: 'productId',
          example: 'P-3001'
        },
        {
          field: 'deliveryDate',
          label: '交付日期',
          dataType: 'date',
          required: true,
          width: 12,
          example: '2023-12-31'
        },
        {
          field: 'quantity',
          label: '数量',
          dataType: 'number',
          required: true,
          width: 10,
          example: 100
        },
        {
          field: 'priority',
          label: '优先级',
          dataType: 'string',
          required: true,
          width: 10,
          options: ['高', '中', '低'],
          example: '高'
        },
        {
          field: 'description',
          label: '备注说明',
          dataType: 'string',
          required: false,
          width: 20,
          example: '加急处理'
        }
      ],
      examples: [
        {
          workOrderId: 'W-001',
          orderId: 'O-1001',
          productId: 'P-3001',
          deliveryDate: '2023-12-31',
          quantity: 100,
          priority: '高',
          description: '加急处理'
        },
        {
          workOrderId: 'W-002',
          orderId: 'O-1002',
          productId: 'P-3002',
          deliveryDate: '2023-12-25',
          quantity: 50,
          priority: '中',
          description: '正常生产'
        }
      ],
      validations: {
        // Excel数据验证规则配置
        priority: {
          type: 'list',
          formula: '高,中,低'
        },
        quantity: {
          type: 'decimal',
          operator: 'greaterThan',
          formula: '0'
        }
      }
    },
    {
      name: '工艺路线',
      dataSource: 'processRoutes',
      columns: [
        {
          field: 'workOrderId',
          label: '工单编号',
          dataType: 'string',
          required: true,
          width: 15,
          example: 'W-001'
        },
        {
          field: 'stepId',
          label: '工序编号',
          dataType: 'string',
          required: true,
          width: 15,
          example: 'S-001'
        },
        {
          field: 'stepName',
          label: '工序名称',
          dataType: 'string',
          required: true,
          width: 20,
          example: '切割'
        },
        {
          field: 'sequence',
          label: '工序顺序',
          dataType: 'number',
          required: true,
          width: 10,
          example: 1
        },
        {
          field: 'standardTime',
          label: '标准工时(分钟)',
          dataType: 'number',
          required: true,
          width: 15,
          example: 30
        },
        {
          field: 'equipmentType',
          label: '设备类型',
          dataType: 'string',
          required: true,
          width: 15,
          example: '切割机'
        }
      ],
      examples: [
        {
          workOrderId: 'W-001',
          stepId: 'S-001',
          stepName: '切割',
          sequence: 1,
          standardTime: 30,
          equipmentType: '切割机'
        },
        {
          workOrderId: 'W-001',
          stepId: 'S-002',
          stepName: '组装',
          sequence: 2,
          standardTime: 45,
          equipmentType: '组装台'
        }
      ]
    }
  ]
}

/**
 * 设备模板配置
 */
export const deviceTemplate = {
  type: 'device',
  name: '设备信息模板',
  description: '用于导入设备相关数据',
  businessType: 'device',
  sheets: [
    {
      name: '设备基础信息',
      dataSource: 'devices',
      columns: [
        {
          field: 'deviceId',
          label: '设备编号',
          dataType: 'string',
          required: true,
          width: 15,
          example: 'DEV-001'
        },
        {
          field: 'deviceName',
          label: '设备名称',
          dataType: 'string',
          required: true,
          width: 20,
          example: '数控切割机1号'
        },
        {
          field: 'deviceType',
          label: '设备类型',
          dataType: 'string',
          required: true,
          width: 15,
          example: '切割机'
        },
        {
          field: 'workshop',
          label: '所属车间',
          dataType: 'string',
          required: true,
          width: 15,
          example: '生产车间A'
        },
        {
          field: 'capacity',
          label: '产能(件/小时)',
          dataType: 'number',
          required: true,
          width: 15,
          example: 10
        },
        {
          field: 'status',
          label: '设备状态',
          dataType: 'string',
          required: true,
          width: 12,
          options: ['正常', '维修', '停用'],
          example: '正常'
        }
      ],
      examples: [
        {
          deviceId: 'DEV-001',
          deviceName: '数控切割机1号',
          deviceType: '切割机',
          workshop: '生产车间A',
          capacity: 10,
          status: '正常'
        }
      ]
    },
    {
      name: '设备工作时间',
      dataSource: 'deviceSchedules',
      columns: [
        {
          field: 'deviceId',
          label: '设备编号',
          dataType: 'string',
          required: true,
          width: 15,
          example: 'DEV-001'
        },
        {
          field: 'dayOfWeek',
          label: '星期',
          dataType: 'string',
          required: true,
          width: 10,
          options: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
          example: '周一'
        },
        {
          field: 'startTime',
          label: '开始时间',
          dataType: 'string',
          required: true,
          width: 12,
          example: '08:00'
        },
        {
          field: 'endTime',
          label: '结束时间',
          dataType: 'string',
          required: true,
          width: 12,
          example: '18:00'
        },
        {
          field: 'breakStart',
          label: '休息开始',
          dataType: 'string',
          required: false,
          width: 12,
          example: '12:00'
        },
        {
          field: 'breakEnd',
          label: '休息结束',
          dataType: 'string',
          required: false,
          width: 12,
          example: '13:00'
        }
      ],
      examples: [
        {
          deviceId: 'DEV-001',
          dayOfWeek: '周一',
          startTime: '08:00',
          endTime: '18:00',
          breakStart: '12:00',
          breakEnd: '13:00'
        }
      ]
    }
  ]
}

/**
 * 人员模板配置
 */
export const personnelTemplate = {
  type: 'personnel',
  name: '人员信息模板',
  description: '用于导入人员相关数据',
  businessType: 'personnel',
  sheets: [
    {
      name: '人员基础信息',
      dataSource: 'personnel',
      columns: [
        {
          field: 'employeeId',
          label: '员工编号',
          dataType: 'string',
          required: true,
          width: 15,
          example: 'EMP-001'
        },
        {
          field: 'employeeName',
          label: '员工姓名',
          dataType: 'string',
          required: true,
          width: 15,
          example: '张三'
        },
        {
          field: 'department',
          label: '所属部门',
          dataType: 'string',
          required: true,
          width: 15,
          example: '生产部'
        },
        {
          field: 'position',
          label: '职位',
          dataType: 'string',
          required: true,
          width: 15,
          example: '操作员'
        },
        {
          field: 'skillLevel',
          label: '技能等级',
          dataType: 'string',
          required: true,
          width: 12,
          options: ['初级', '中级', '高级', '专家'],
          example: '中级'
        },
        {
          field: 'hourlyRate',
          label: '小时工资',
          dataType: 'number',
          required: true,
          width: 12,
          example: 25.5
        }
      ],
      examples: [
        {
          employeeId: 'EMP-001',
          employeeName: '张三',
          department: '生产部',
          position: '操作员',
          skillLevel: '中级',
          hourlyRate: 25.5
        }
      ]
    },
    {
      name: '人员技能',
      dataSource: 'personnelSkills',
      columns: [
        {
          field: 'employeeId',
          label: '员工编号',
          dataType: 'string',
          required: true,
          width: 15,
          example: 'EMP-001'
        },
        {
          field: 'skillName',
          label: '技能名称',
          dataType: 'string',
          required: true,
          width: 20,
          example: '数控操作'
        },
        {
          field: 'proficiency',
          label: '熟练度',
          dataType: 'number',
          required: true,
          width: 12,
          example: 85
        },
        {
          field: 'certificationDate',
          label: '认证日期',
          dataType: 'date',
          required: false,
          width: 15,
          example: '2023-01-15'
        }
      ],
      examples: [
        {
          employeeId: 'EMP-001',
          skillName: '数控操作',
          proficiency: 85,
          certificationDate: '2023-01-15'
        }
      ]
    }
  ]
}

/**
 * 模板管理器类
 */
export class TemplateManager {
  constructor() {
    this.templates = new Map()
    this.businessTypes = new Map()
    
    // 注册默认模板
    this.registerTemplate(workOrderTemplate)
    this.registerTemplate(deviceTemplate)
    this.registerTemplate(personnelTemplate)
  }

  /**
   * 注册模板
   * @param {Object} template - 模板配置
   */
  registerTemplate(template) {
    this.templates.set(template.type, template)
    
    if (!this.businessTypes.has(template.businessType)) {
      this.businessTypes.set(template.businessType, [])
    }
    this.businessTypes.get(template.businessType).push(template)
  }

  /**
   * 获取模板
   * @param {string} templateType - 模板类型
   * @returns {Object|null} 模板配置
   */
  getTemplate(templateType) {
    return this.templates.get(templateType) || null
  }

  /**
   * 获取业务类型的模板列表
   * @param {string} businessType - 业务类型
   * @returns {Array} 模板列表
   */
  getTemplatesByBusinessType(businessType) {
    return this.businessTypes.get(businessType) || []
  }

  /**
   * 获取所有模板
   * @returns {Array} 所有模板列表
   */
  getAllTemplates() {
    return Array.from(this.templates.values())
  }

  /**
   * 获取模板的映射配置
   * @param {string} templateType - 模板类型
   * @returns {Object} 映射配置
   */
  getTemplateMappingConfig(templateType) {
    const template = this.getTemplate(templateType)
    if (!template) return {}

    const mappingConfig = {}
    for (const sheet of template.sheets) {
      mappingConfig[sheet.name] = sheet.columns.map(column => ({
        excelColumn: column.label,
        targetField: column.field,
        dataType: column.dataType,
        required: column.required || false,
        validationRule: column.validationRule || '',
        validator: column.validator || '',
        transformer: column.transformer || '',
        options: column.options || []
      }))
    }

    return mappingConfig
  }

  /**
   * 创建自定义模板
   * @param {Object} templateConfig - 自定义模板配置
   * @returns {Object} 创建的模板
   */
  createCustomTemplate(templateConfig) {
    const template = {
      type: templateConfig.type || `custom_${Date.now()}`,
      name: templateConfig.name || '自定义模板',
      description: templateConfig.description || '',
      businessType: templateConfig.businessType,
      sheets: templateConfig.sheets || [],
      custom: true,
      createdAt: new Date().toISOString()
    }

    this.registerTemplate(template)
    return template
  }

  /**
   * 更新模板
   * @param {string} templateType - 模板类型
   * @param {Object} updates - 更新内容
   * @returns {boolean} 是否更新成功
   */
  updateTemplate(templateType, updates) {
    const template = this.getTemplate(templateType)
    if (!template) return false

    Object.assign(template, updates, {
      updatedAt: new Date().toISOString()
    })

    return true
  }

  /**
   * 删除模板
   * @param {string} templateType - 模板类型
   * @returns {boolean} 是否删除成功
   */
  deleteTemplate(templateType) {
    const template = this.getTemplate(templateType)
    if (!template || !template.custom) return false

    this.templates.delete(templateType)
    
    // 从业务类型列表中移除
    const businessTemplates = this.businessTypes.get(template.businessType)
    if (businessTemplates) {
      const index = businessTemplates.findIndex(t => t.type === templateType)
      if (index !== -1) {
        businessTemplates.splice(index, 1)
      }
    }

    return true
  }

  /**
   * 验证模板配置
   * @param {Object} template - 模板配置
   * @returns {Object} 验证结果
   */
  validateTemplate(template) {
    const errors = []

    if (!template.type) {
      errors.push('模板类型不能为空')
    }

    if (!template.name) {
      errors.push('模板名称不能为空')
    }

    if (!template.businessType) {
      errors.push('业务类型不能为空')
    }

    if (!template.sheets || template.sheets.length === 0) {
      errors.push('至少需要一个工作表配置')
    }

    for (let i = 0; i < template.sheets.length; i++) {
      const sheet = template.sheets[i]
      
      if (!sheet.name) {
        errors.push(`第${i + 1}个工作表名称不能为空`)
      }

      if (!sheet.columns || sheet.columns.length === 0) {
        errors.push(`第${i + 1}个工作表至少需要一个列配置`)
      }

      for (let j = 0; j < sheet.columns.length; j++) {
        const column = sheet.columns[j]
        
        if (!column.field) {
          errors.push(`第${i + 1}个工作表第${j + 1}列字段名不能为空`)
        }

        if (!column.label) {
          errors.push(`第${i + 1}个工作表第${j + 1}列标签不能为空`)
        }

        if (!column.dataType) {
          errors.push(`第${i + 1}个工作表第${j + 1}列数据类型不能为空`)
        }
      }
    }

    return {
      valid: errors.length === 0,
      errors
    }
  }
}

// 创建默认实例
export const templateManager = new TemplateManager()

export default TemplateManager






